package operate

import (
	"errors"
	"gin-demo/common"
	"gin-demo/container"
	"gin-demo/entity"
	"gorm.io/gorm"
)

type RecordDaoImp struct {
}

func (c RecordDaoImp) List(pageRequest common.PageRequest) (*entity.RecordList, error) {

	offset, limit := common.PageHandle(pageRequest)
	var records []*entity.Record
	var recordDB = container.Get("db").(*gorm.DB)
	err := recordDB.
		Table("record").
		Offset(offset).
		Limit(limit).
		Find(&records).Error
	var count int64
	err = recordDB.
		Table("record").
		Count(&count).Error
	if err != nil {
		return nil, err
	}

	var pageResponse common.PageResponse
	pageResponse.Total = count
	pageResponse.PageInfo = pageRequest
	recordList := &entity.RecordList{
		PageResponse: pageResponse,
		Records:      records,
	}
	return recordList, nil

}

func (c RecordDaoImp) Insert(record *entity.Record) error {
	var recordDB = container.Get("db").(*gorm.DB)
	err := recordDB.
		Table("record").
		Create(&record).Error
	if err != nil {
		return errors.New("调用Insert 失败")
	}
	return nil
}
